package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.annotation.UserLoginToken;
import com.example.demo.entity.User;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import com.example.demo.unit.TokenUnit;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
public class LoginController {

	@Autowired
	private UserService userService;


	@Autowired
	private TokenService tokenService;

    @ApiOperation(value = "登录")
    @GetMapping("/login")
    public JSONObject login(User user, HttpServletResponse response) {
        User result = userService.findByUserId(user.getId());
        JSONObject jsonObject = new JSONObject();
        if (!result.getPassword().equals(user.getPassword())) {
            jsonObject.put("message", "密码错误");
        } else {
            String token = tokenService.getToken(result);
            System.out.println(token);
            jsonObject.put("token", token);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return jsonObject;
    }

	// 这个请求需要token才能访问
	@UserLoginToken
	@RequestMapping(value = "/getMessage",method = RequestMethod.GET)
	public String message(){
        System.out.println(TokenUnit.getTokenId());
        return "你已经通过验证";
	}

	@GetMapping(value = "/go")
	public Object login2(){
        System.out.println(2);
	    JSONObject jsonObject = new JSONObject();
	    jsonObject.put("message","hello");
	    return jsonObject;
    }
	
}
